<template>
  <div class="mainCon">
    <div class="mainCon">
      <div class="containercontent">
        <div class="treeDivStyle inlineblock">
          <div class="oprate">
            <!--物资类型-->
            <el-button type="primary" size="mini" style="float:right;margin-right:5px;" v-if = "userOpernation.delete.display" @click="deleteattachType()" :disabled="attachTypeInfo.id== undefined || attachTypeInfo.id== '' || attachTypeInfo.id== null || attachTypeInfo.parent == 'lab'">删除</el-button>
            <el-button type="primary" size="mini" style="float:right;margin-right:5px;margin-left:0;" v-if = "userOpernation.update.display" @click="editattachType('edit')"
              :disabled="attachTypeInfo.id== undefined || attachTypeInfo.id== '' || attachTypeInfo.parent == 'lab'">修改</el-button>
            <el-button type="primary" size="mini" style="float:right;margin-right:5px;" v-if = "userOpernation.add.display" @click="attachTypeAdd" :disabled="attachTypeInfo.id== undefined || attachTypeInfo.id== ''|| attachTypeInfo.id== null">新增</el-button>
          </div>
          <!--:node-key="id"-->
          <el-tree :data="attachmentTypeList" :props="defaultProps" @node-click="handleNodeClick" ref="treeBox" node-key="id" :default-checked-keys="arrHight"
            :expand-on-click-node="false" default-expand-all :highlight-current="true"></el-tree>
        </div>
        <div class="inlineblock treeRightCon">
          <div class="seachTip selectw100">
            <div class="inlineblock verticalmiddle infoitem">
              <div class="inlineblock verticalmiddle">
                文件
              </div>
              <div class="inlineblock verticalmiddle informationItem">
                <el-input v-model="searchName" size="mini" placeholder="名称" @keyup.enter.native="readattchList(attachQuery)"></el-input>
              </div>
            </div>
            <div class="inlineblock basicRightDistanceA searchIcon">
              <el-button size="mini" @click="readattchList(attachQuery)">搜索</el-button>
            </div>
          </div>

          <div class="separaterowTable">
            <div class="tableTittle">
              <div><span class="fontImpact">1</span><span>文件列表</span></div>
              <el-button type="primary" icon="el-icon-plus" size="mini"  v-if = "userOpernation.upload.display" style="float:right" @click="uploadClick" :disabled="attachTypeInfo.id== undefined || attachTypeInfo.id== ''|| attachTypeInfo.id== null">上传文件</el-button>
              <form id="fileForm">
                <input type="file" name="file" id="fileBtn" @change="upload" multiple>
              </form>

            </div>
            <el-table :data="attachList" size='mini' class="tableCon">
              <el-table-column label="序号" fixed min-width="50px">
                <template slot-scope="scope">
                  {{scope.$index+(attachQuery.page - 1) * attachQuery.pageCount + 1}}
                </template>
              </el-table-column>
              <el-table-column prop="fileName" label="名称" :show-overflow-tooltip = "true">
              </el-table-column>
              <el-table-column prop="fileSize" label="大小">
                <template slot-scope="scope">
                  {{scope.row.fileSize == 0 ? 1 : scope.row.fileSize }} KB
                </template>
              </el-table-column>
              <el-table-column property="createByName" label="上传人" min-width="80px">
              </el-table-column>
              <el-table-column property="createTime" label="上传时间" min-width="100px" :formatter="timeFormatter">
              </el-table-column>
              <el-table-column label="操作" min-width="100px">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="deleteattachment(scope.row)" v-if = "userOpernation.delete.display">删除</el-button>
                  <el-button type="text" size="mini" @click="downloadattachment(scope.row)" v-if = "userOpernation.download.display">下载</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="block changepages">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="attachQuery.page" :page-sizes="[20,30,40]"
                :page-size="attachQuery.pageCount" layout="total, sizes, prev, pager, next, jumper" :total="rowNumber">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
    <add-attach-type :addVisible.sync='addAttachmentType' :newOrEdit="newOrEdit" :attachTypeInfo="attachTypeInfo"></add-attach-type>

  </div>
</template>

<script>
  import { mapState } from 'vuex'
  const addAttachType = () => import('./children/addAttachType.vue');



  export default {
    data() {
      return {
        attachmentTypeList: [], //物资类型
        addAttachmentType: false, //添加物资类型
        defaultProps: {  //物资列表树继承的值
          children: 'fileTypeBeans',
          label: 'name',
          value: 'id'
        },
        newOrEdit: 'new',//是新增还是编辑
        attachTypeInfo: {}, //点击的物资类型的信息
        arrHight: [], //树高亮显示的数组
        searchName: '',
        attachList: [], //物资列表
        attachQuery: {
          page: 1, //第几页
          pageCount: 20, //页面得记录条数，
        },
        rowNumber: 0,
        newOrEditMaterial: 'new', //是新增还是编辑物资列表
        addMaterialShow: false, //添加物资列表弹出
        marterialInfo: {}, //物资列表


      }
    },
    computed: {
      ...mapState(['enableStatus', 'tableHeightB', 'typeofAbilityTableDate', 'materialType', 'manujson']),
    },
    props: ['userOpernation'],
    components: {
      addAttachType
    },
    mounted() {
      this.readattachmentTypeList();
      this.readattchList(this.attachQuery);
    },
    watch: {
      attachQuery: {
        handler(val, oldVal) {
          this.readattchList(this.attachQuery)
        },
        deep: true
      },
    },
    methods: {
      formatter(row, column, cellValue, index) {
        return this.util.changeStatus({ cellValue: cellValue, list: this.enableStatus })
      },
      timeFormatter(row, column, cellValue, index) {
        return this.util.formatterDate({ cellValue: cellValue })
      },
      //读取文档类型列表
      readattachmentTypeList(nid) {
        this.$http({
          method: 'post',
          apiUrl: '/technology/readLabFileTypes.htm',
        }).then(res => {
          if (res.code === 0) {
            this.attachmentTypeList = res.data;
            if (nid) {
              this.arrHight.push(nid);
              this.$nextTick(() => {
                this.$refs.treeBox.setCurrentKey(nid);// treeBox 元素的ref   value 绑定的node-key

              });
            }

          }
        })
      },

      // 添加文档类型
      attachTypeAdd() {
        this.addAttachmentType = true;
        this.newOrEdit = 'new'
      },
      //  点击文档类型树
      handleNodeClick(val) {
        console.log(val)
        this.attachTypeInfo = val;
        this.attachQuery.page = 1;
        this.readattchList(this.attachQuery)
      },
      // 编辑文档类型
      editattachType(newOrEdit) {
        this.addAttachmentType = true;
        this.newOrEdit = newOrEdit;
      },
      // 删除文档类型
      deleteattachType(row) {
        this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var that = this;
          var url = "/technology/deleteLabFileType.htm"
          var data = {
            id: this.attachTypeInfo.id,
          }
          this.$http({
            apiUrl: url,
            type: 'post',
            params: data,
          }).then(res => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
                this.attachTypeInfo = {};  //删除之后选中节点置为空
                this.readattachmentTypeList()  //删除之后刷新树
                this.handleNodeClick(this.attachTypeInfo)
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 读取文档列表
      readattchList(parp) {
        var data = {
          ids: this.attachTypeInfo.id,
          islab: true,
          fileName: this.searchName,
          page: parp.page,
          pageCount: parp.pageCount,
        }
        if(this.attachTypeInfo.parent == 'lab'){
            data.ids = null;
        }
        this.$http({
          method: 'post',
          apiUrl: '/download/getFilePathByPage.htm',
          params: data,
          isJson: true,
        }).then(res => {
          if (res.code === 0) {
            this.attachList = res.data;
          }
          if (!res.pageinfo) {
            this.rowNumber = 0;
          } else if (res.pageinfo && !res.pageinfo.rowNumber) {
            this.rowNumber = 0;
          } else {
            this.rowNumber = res.pageinfo.rowNumber;
          }
        })
      },
      // 模拟file的点击事件
      uploadClick() {
        document.getElementById("fileBtn").click()
      },
      // 中心上传文件
      upload(event) {
        var files = document.getElementById('fileBtn').files
        var formData = new FormData();
        for(var i of files){
            formData.append('file', i)
        }
        // formData.append('file', files)
        formData.append('ids', this.attachTypeInfo.id)
        formData.append('taskType', null)
        formData.append('detectability', null)
        formData.append('sign', this.attachTypeInfo.sign)
        this.$axios({
          method: 'post',
          url: '/technology/upLoadLabAttachment.htm',
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data',
            'token':sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined,
           }
        }).then(res => {
          var data = res.data
          event.target.value= "";
          if (data.code == 0) {
            this.$notify({
              title: '消息',
              message: '上传成功',
              type: 'success'
            })
            this.readattchList(this.attachQuery);
          } else {
            this.$message({
              type: 'info',
              message: data.description,
            })
          }

        })
      },
      //删除方法附件
      deleteattachment(row) {
        this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            method: 'post',
            apiUrl: '/download/fileDelete.htm',
            params: {
              id: row.id,
            },
            isJson: false,
          }).then(res => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.readattchList(this.attachQuery)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 下载附件
      downloadattachment(row) {
        var url = "/download/fileDownload.htm"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
        window.open(process.env.baseUrl + url + '?id=' + row.id + "&token=" + token);
      },
      handleCurrentChange(val) {
        this.attachQuery.page = val;
      },
      handleSizeChange(val) {
        this.attachQuery.pageCount = val;
      },



    }
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .treeDivStyle {
    width: 25%;
    height: 100%;
    /* overflow-y: scroll; */
    overflow-x: auto;
    background: #fff;
  }
  .treeDivStyle .el-tree{
      height: calc(100% - 40px);
      overflow-y: scroll;
      overflow-x: auto;
  }

  .treeRightCon {
    width: 73%;
    height: 100%;
    vertical-align: top;
  }

  .treeDivStyle .oprate {
    height: 40px;
    padding-top: 5px;
    border-bottom: 1px solid #dadada;
  }

  #fileBtn {
    width: 50px;
    height: 20px;
    opacity: 0;
    position: absolute;
    left: 0;
    top: 0;
    z-index: -1;
  }
</style>
